package com.ftg.learn.chapter02.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

/**
 * 做mybatis通用方法处理的 -
 *
 * @param <T>    关联对象
 * @author kangjx
 * @version 1.0
 * @date 2023/12/22 上午9:06
 */
public class MybatisUtil<T> {

    /**
     * 配置文件的路径
     */
    private String MYBATIS_DEFAULT_PATH = "configinterface/zong.xml";

    public MybatisUtil(){
    }

    public MybatisUtil(String path){
        this.MYBATIS_DEFAULT_PATH = path;
    }

    /**
     * 获取sqlSessionFactory
     * @return
     */
    public SqlSessionFactory getSqlSessionFactory(){
        try {
            Reader reader = Resources.getResourceAsReader(MYBATIS_DEFAULT_PATH);
            return new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 获取sqlSession
     * @return
     */
    public SqlSession getSqlSession(){
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        return sqlSessionFactory.openSession();
    }


    /**
     * 获取mapper  Sysuser.class
     * @param clazz  关联对象 Sysuser.class
     * @param <T>    目标    Sysuser
     * @return
     */
    public T getMapper(Class<T> clazz){
        SqlSession sqlSession = getSqlSession();
        return sqlSession.getMapper(clazz);
    }

    /**
     * 关闭sqlSession
     * @param sqlSession  连接
     */
    public void closeSession(SqlSession sqlSession){
        if(null!= sqlSession){
            getSqlSession().close();
        }
    }

    /**
     * 提交sqlSession
     * @param sqlSession  连接
     */
    public void commitSession(SqlSession sqlSession){
        if(null!= sqlSession){
            sqlSession.commit();
        }
    }

    /**
     * 回滚sqlSession
     * @param sqlSession  连接
     */
    public void rollbackSession(SqlSession sqlSession){
        if(null!= sqlSession){
            sqlSession.rollback();
        }
    }

}
